package com.badger.generator.base.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.badger.generator.base.entity.BaseEntity;
import com.badger.generator.base.service.BaseService;
import com.badger.generator.constant.CodeConstants;
import com.badger.generator.constant.Result;

import lombok.extern.slf4j.Slf4j;

/**
 * 父级的controller
 * @author liqi
 */
@Slf4j
public class ApiController<T extends BaseEntity> extends BaseController {
    @Autowired
    BaseService<T> service;

    /**
     * 数据保存或更新
     * @param entity
     * @return
     */
    @RequestMapping(value = { "save", "update" })
    public String saveOrEdit(@RequestBody @Valid T entity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<String, String>(16);
            List<FieldError> list = bindingResult.getFieldErrors();
            for (FieldError error : list) {
                map.put(error.getField(), error.getDefaultMessage());
            }
            log.error(JSON.toJSONString(map));
            return Result.getInstance(CodeConstants.RESULT_FAIL, map).toString();
        }
        if (super.getRequestUrl().endsWith("update")) {
            service.updateNotNull(entity);
        } else if (super.getRequestUrl().endsWith("save")) {
            service.save(entity);
        }
        return Result.getInstance(entity).toString();
    }

    /**
     * 根据实体的属性，查询列表数据
     * @param entity
     * @return json
     */
    @RequestMapping(value = "select")
    public String select(@RequestBody T entity) {
        return Result.getInstance(service.select(entity)).toString();
    }

    /**
     * 根据查询条件，查询分页数据
     * @param entity
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "pageInfo")
    public String pageInfo(@RequestBody T entity, @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize") Integer pageSize) {
        return Result.getInstance(CodeConstants.RESULT_SUCCESS, service.selectPageInfo(entity, page, pageSize))
                .toString();
    }

    /**
     * 根据主键，查询单条数据
     * @param key
     * @return
     */
    @RequestMapping(value = "selectByKey")
    public String selectByKey(@RequestParam(value = "key") Object key) {
        return Result.getInstance(service.selectByKey(key)).toString();
    }
}
